﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Delay;
using System.Diagnostics;

namespace PhoneInfo.Page
{
   
    
     public partial class DownloadManager : PhoneApplicationPage
    {
       private InboxObject Inbox;
       private string appid="";
       static int first = 0;
        public DownloadManager()
        {
            InitializeComponent();
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            Inbox = new InboxObject();
            listbox.DataContext = Inbox;
            IDictionary<string, string> parameters = this.NavigationContext.QueryString;
            if (parameters.ContainsKey("appid"))
            {
                appid = parameters["appid"];
            }
            if (appid.Length > 0)
            {
                //从list点击进来的需要添加下载
                Inbox[0].PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(type_PropertyChanged);
                Inbox[1].PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(type_PropertyChanged);
                Inbox[0].SetValue(LowProfileXmlLoader.UriSourceProperty, new Uri(Inbox[0].GetPhoneInfoUrl(appid, 0)));
            }
            else
            {
                if (Inbox[0].Item.Count>0)
                {
                    Inbox[0].IsExpanded = true;
                }
                if (Inbox[1].Item.Count > 0)
                {
                    Inbox[1].IsExpanded = true;
                }
                ProgBar.Visibility = Visibility.Collapsed;
            }
        }
        void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (sender == null)
            {
                return;
            }
            if (sender is DowloadManagerItem)
            {
                DowloadManagerItem item = sender as DowloadManagerItem;
                if (item == null)
                {
                    return;
                }
                if (e.PropertyName == "Result")
                {
                    if (item.Result == 1)
                    {//下载已完成
                        App.ManagerDB.SubmitChanges();
                    }
                    Debug.WriteLine("has file size:{0},total file size {1}", item.HasFilesize, item.TotalSize);
                    for (int i = 0; i < 2; i++)
                    {
                        Inbox[i].Item = new ObservableCollection<DowloadManagerItem>(Inbox.loadDB(i));
                        if (Inbox[i].Item.Count != 0)
                        {
                            Inbox[i].ExpanderInfo = "收起";
                        }
                        else
                        {
                            Inbox[i].ExpanderInfo = "列表为空";
                        }
                        Inbox[1].IsExpanded = true;
                    }
                    //重新加载

                }
                
                else if (e.PropertyName == "HasFilesize")
                {
                    if (item.HasFilesize > 0)
                    {
                        if(first==0)
                        {
                            first = 1;
                            Inbox[0].IsExpanded = true;
                        }
                        Debug.WriteLine("has file size:{0},total file size {1}", item.HasFilesize,item.TotalSize);
                        App.ManagerDB.SubmitChanges();
                    }
                }   
            }
        }
        void type_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (sender == null)
            {
                return;
            }
           
            if (sender is ConversationObject)
            {
                ConversationObject sdv = sender as ConversationObject;
                if (sdv == null)
                {
                    return;
                }
                if (e.PropertyName == "Result")
                {
                    switch (sdv.Result)
                    {
                        case -1:
                        case 1:
                            ProgBar.Visibility = Visibility.Collapsed;
                            ToastPrompt toast = new ToastPrompt()
                            {
                                Message = sdv.ResultMsg
                            };
                            break;
                        case 2:
                            ProgBar.Visibility = Visibility.Collapsed;
                            var userInDB = (from DowloadManagerItem user in App.ManagerDB.DowloadItemTable
                                            select user).ToList();
                            bool isExist = false;
                            foreach (DowloadManagerItem it in userInDB)
                            {//
                                if (it.Appid == sdv.Item[sdv.Item.Count - 1].Appid)
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            if (isExist == true)
                            {
                                ToastPrompt tmp = new ToastPrompt()
                                {
                                    Message = "该软件已经在下载！请单击列表查看"
                                };
                                tmp.Show();
                            }
                            else
                            {
                                sdv.Item[sdv.Item.Count - 1].Type = "prog";
                                sdv.ExpanderInfo = "展开";
                                App.ManagerDB.DowloadItemTable.InsertOnSubmit(sdv.Item[sdv.Item.Count - 1]);
                                App.ManagerDB.SubmitChanges();
                                sdv.Item[sdv.Item.Count - 1].PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(item_PropertyChanged);
                                sdv.Item[sdv.Item.Count - 1].SetValue(NetWork.UriSourceProperty, new Uri(sdv.Item[sdv.Item.Count - 1].Downurl));
                            }
                            break;
                    }

                }
                else if (e.PropertyName == "IsExpanded")
                {

                    if (sdv.IsExpanded == true)
                    {
                        sdv.ExpanderInfo = "收起";
                    }
                    else
                    {
                        sdv.ExpanderInfo = "展开";
                    }
                }
            }
        }
        private void StackPanel_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (sender==null)
            {
                return;
            }
            StackPanel sp = sender as StackPanel;
            if (sp==null)
            {
                return;
            }
            DowloadManagerItem item = sp.DataContext as DowloadManagerItem;
            if (item==null)
            {
                return;
            }
            if (item.Type == "prog")
            {
                item.Type = "pause";
            }
            else if (item.Type == "pause")
            {
                item.Type = "start";
                item.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(item_PropertyChanged);
                item.SetValue(NetWork.UriSourceProperty, new Uri(item.Downurl));
            }
            else
            {
                return;
            }
        }

        private void Cancel(object sender, RoutedEventArgs e)
        {
            if (sender == null)
            {
                return;
            }
            MenuItem sp = sender as MenuItem;
            if (sp == null)
            {
                return;
            }
            DowloadManagerItem item = sp.DataContext as DowloadManagerItem;
            if (item==null)
            {
                return;
            }
            if (item.Type == "complate")
            {
                Inbox[1].Item.Remove(item);
            }
            else
            {
                Inbox[0].Item.Remove(item);
            }
        }
    }
     public class InboxObject : ObservableCollection<ConversationObject>
     {
         public InboxObject()
             : base()
         {
             this.Add(new ConversationObject("最近下载"));
             this.Add(new ConversationObject("历史下载"));
             for (int i = 0; i < 2; i++)
             {
                 this[i].Item = new ObservableCollection<DowloadManagerItem>(loadDB(i));
                 if (this[i].Item.Count != 0)
                 {
                     if (this[i].IsExpanded == true)
                     {
                         this[i].ExpanderInfo = "收起";
                     }
                     else
                     {
                         this[i].ExpanderInfo = "展开";
                     }
                   
                 }
                 else
                 {
                     this[i].ExpanderInfo = "列表为空";
                 }

             }

         }
         private bool IsEmptyDB()
         {
             var userInDB = from DowloadManagerItem user in App.ManagerDB.DowloadItemTable
                            select user;
             foreach (var item in userInDB)
             {
                 return false;
             }
             return true;
         }
         public List<DowloadManagerItem> loadDB(int type)
         {

             if (type == 0)
             {//未下载完成的列表
                 var userInDB = (from DowloadManagerItem user in App.ManagerDB.DowloadItemTable
                                 where user.Type == "ready" || user.Type == "prog"
                                 select user).ToList();
                 return userInDB;
             }
             else
             {//已经下载完成的列表
                 var userInDB = (from DowloadManagerItem user in App.ManagerDB.DowloadItemTable
                                 where user.Type == "complate"
                                 select user).ToList();
                 return userInDB;
             }

         }

     }
}